<!--
 * @Author: 谢陈洁
 * @Date: 2025-05-26 09:31:16
 * @LastEditors: 谢陈洁
 * @LastEditTime: 2025-08-01 10:37:11
 * @Description: file content
-->
<template>
  <el-card class="profile-card" header="个人信息">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="基本信息" name="basic">
        <dynamic-form
          ref="formRef"
          :form-config="formConfig"
          v-model="userInfo"
          @submit-success="handleSubmitSuccess"
        />
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="pwd">
        <dynamic-form
          ref="pwdFormRef"
          :form-config="passwordFormConfig"
          @submit-success="handlePwdSubmitSuccess"
        />
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <base-button @click="handleSubmit">保存修改</base-button>
    </template>
  </el-card>
</template>

<script setup>
  import { ref } from 'vue'
  import { Plus } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { useUserStore } from '@/stores/userStore'
  import { storeToRefs } from 'pinia'
  import { formConfig, passwordFormConfig } from './config'
  import { changePassword, saveUserInfo } from '@/services/apis/system/user'
  const userStore = useUserStore()
  const { userInfo } = storeToRefs(userStore)
  const formRef = ref(null)
  const pwdFormRef = ref(null)
  const activeTab = ref('basic')
  const handleSubmit = () => {
    if (activeTab.value === 'basic') {
      formRef.value?.handleSubmit()
    } else {
      pwdFormRef.value?.handleSubmit()
    }
  }
  const handleSubmitSuccess = async data => {
    const formData = new FormData()
    for (const key in data) {
      if (key === 'avatar') {
        formData.append(key, data.avatar[0].raw || data.avatar[0].url)
      } else {
        formData.append(key, data[key])
      }
    }
    // todo: 图片还没有处理，需要上传到服务器  等域名备案后，再上传到服务器
    const res = await saveUserInfo(formData)
    ElMessage.success(res.message || '保存成功')
    userStore.getUserInfo(true)
  }
  const handlePwdSubmitSuccess = async data => {
    const res = await changePassword(data)
    ElMessage.success(res.message || '修改成功')
  }
  onMounted(() => {
    userStore.getUserInfo(true)
  })
</script>

<script>
  export default {
    name: 'Profile'
  }
</script>

<style scoped lang="scss">
  .profile-card {
    max-height: 100%;
    display: flex;
    flex-direction: column;
    :deep(.el-card__body) {
      flex: 1;
      overflow: auto;
    }
  }
</style>
